package cascade.controller.pages.commands
{
	import cascade.model.Page;
	
	import flash.events.Event;
	
	import flight.commands.AsyncCommand;

	public class CommandSelectPage extends AsyncCommand
	{
		
		public var page:Page;
		public var draftMode:Boolean;
		
		public function CommandSelectPage(page:Page, draftMode:Boolean = false)
		{
			this.page = page;
			this.draftMode = draftMode;
		}
		
		public override function execute():*
		{
			// no changing pages when in edit mode!! :)
			if (Cascade.view.editing || !page)
				return;
			
			Cascade.view.draftMode = draftMode;
			
			// assemble the url with draft and/or testing parameters
			var url:String = page.url;
			if (draftMode && page.liveRevision != null)
				url += "?draft";
			
			if (Cascade.view.debug)
				url += (url.indexOf("?") == -1 ? "?" : "&") + "start_debug=1&debug_host=127.0.0.1&debug_port=10000&debug_stop=1";
			
			
			if (!page.revisions)
				Cascade.controller.execCommand("loadRevisions", page);
			
			Cascade.view.currentURL = url;
			
			// indicate the app is busy
			Cascade.busy.addBusy(this);
			Cascade.view.browser.htmlLoader.addEventListener(Event.COMPLETE, pageLoaded);
			
			// determine if the page is already selected in its current and correct state
			if (Cascade.view.browser.location != url)
				Cascade.view.browser.location = url;
		}
		
		protected function pageLoaded(event:Event):void {
			Cascade.view.browser.htmlLoader.removeEventListener(Event.COMPLETE, pageLoaded);
			
			// indicate the app is no longer busy
			Cascade.busy.removeBusy(this);
			
			dispatchExecutionComplete();
		}
	}
}
